package engineer.clientapp.actions;

import java.sql.Connection;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;



import engineer.clientapp.beans.DeleteUser;
import engineer.clientapp.tools.Connector;
import engineer.clientapp.tools.SendEmail;

public class DeleteUserAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	String target = null;
	DeleteUser user=  (DeleteUser)form;
	String email = user.getEmail();
	
	ActionErrors actionErrors = new ActionErrors();
	try{
		if(email.equals("0")){
			target="failure";
			actionErrors.add("info",
					new ActionMessage("error.userNotChoice"));
		}else{
		Connection connection = new Connector().getConnection();
		Statement statement = connection.createStatement();
		statement.executeUpdate("Delete from automats.users where email='"+email+"'");
		SendEmail.sendDeletedEmail(email);
		connection.close();
		target="success";
		actionErrors.add("info",
				new ActionMessage("error.userDeleted"));
		}
	}catch(Exception e){
		e.printStackTrace();
		target="failure";
		actionErrors.add("info",
				new ActionMessage("error.catch"));
	} 
	if(actionErrors.size() !=0){
		extracted(request, actionErrors);
		return new ActionForward(mapping.getInput());
	}
	return mapping.findForward(target);
	

	}
	
	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}
}
